<template>
  <div>
    <el-card
      shadow="never"
      body-style="padding: 20px 20px 0px 20px;background:#FAFAFA"
      style="margin-top: 10px">
      <el-form ref="ruleForm" class="form-options" inline :model="form" label-width="100px">
        <el-form-item label="盘库任务号">
          <el-input v-model="form.checkNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="盘库发起人">
          <el-input
            v-model="form.createName"
            disabled></el-input>
        </el-form-item>
        <el-form-item label="仓库">
          <el-input
            v-model="form.warehouseName"
            disabled/>
        </el-form-item>
        <el-form-item label="盘库时间">
          <el-date-picker
            v-model="form.checkTime"
            disabled
            type="date"
            value-format="yyyy-MM-dd"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="盘库说明" class="long-content">
          <el-input
            type="textarea"
            disabled
            style="width: 700px"
            :rows="4"
            v-model="form.checkExplain"/>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="app-container" style="padding: 0">
      <el-table
        border
        :data="detailTableData"
        header-cell-class-name="table-header"
        style="width: 100%;margin-top: 20px"
        show-overflow-tooltip>
        <el-table-column
          label="序号"
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="parentName"
          show-overflow-tooltip
          label="器材分类">
        </el-table-column>
        <el-table-column
          prop="labelWayName"
          label="贴标方式">
        </el-table-column>
        <el-table-column
          prop="equipmentTypeName"
          show-overflow-tooltip
          label="器材名称">
        </el-table-column>
        <el-table-column
          prop="stockInNum"
          label="应在库数量">
        </el-table-column>
        <el-table-column
          prop="stockInNumReal"
          label="盘点在库数量">
        </el-table-column>
        <el-table-column
          prop="differenceStockInNum"
          label="当前在库差异数量">
        </el-table-column>
        <el-table-column label="处理在库数量异常">
          <template slot-scope='scope'>
            <el-button
              type="danger"
              v-if="scope.row.stockInStatus==2"
              @click="handleExceptionOperateClick(scope.row,'处理在库数量异常')">
              处理异常
            </el-button>
            <el-button
              type="primary"
              v-if="scope.row.stockInStatus==3"
              @click="handleExceptionOperateClick(scope.row,'处理在库数量异常')">
              查看记录
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="stockOutNum"
          label="应在外数量">
        </el-table-column>
        <el-table-column
          prop="stockOutNumReal"
          label="实际在外数量">
        </el-table-column>
        <el-table-column
          prop="differenceStockOutNum"
          label="在外差异数量">
        </el-table-column>
        <el-table-column label="处理在外数量异常">
          <template slot-scope='scope'>
            <el-button
              type="danger"
              v-if="scope.row.stockOutStatus==2"
              @click="handleExceptionOperateClick(scope.row,'处理在外数量异常')">处理异常
            </el-button>
            <el-button
              type="primary"
              v-if="scope.row.stockOutStatus==3"
              @click="handleExceptionOperateClick(scope.row,'处理在外数量异常')">查看记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;margin-top: 20px">
        <el-pagination
          background
          @size-change="handleExceptionSizeChange"
          @current-change="handleExceptionCurrentChange"
          :current-page="currentDetailPage"
          :page-sizes="[10, 15, 30]"
          :page-size="detailPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="detailTotal">
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="selectStock==0?'处理在外数量异常':'处理在库数量异常'"
      top="45px"
      append-to-body
      @close="onDialogClose"
      :visible.sync="dialogVisible"
      width="960px">
      <div class="app-container" style="padding: 0">
        <div v-if="selectDetailData" style="line-height: 22px">器材分类：{{ selectDetailData.parentName }}</div>
        <div v-if="selectDetailData" style="line-height: 22px">器材名称：{{ selectDetailData.equipmentTypeName }}</div>
        <div v-if="selectDetailData" style="line-height: 22px">贴标方式：{{ selectDetailData.labelWayName }}</div>
        <el-table
          border
          :data="tableData"
          @row-click="goMap"
          header-cell-class-name="table-header"
          style="width: 100%;margin-top: 20px"
          show-overflow-tooltip>
          <el-table-column
            label="序号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            prop="labelId"
            label="器材标签ID">
          </el-table-column>
          <el-table-column
            prop="equipmentName"
            show-overflow-tooltip
            label="器材名称">
          </el-table-column>
          <el-table-column
            prop="num"
            label="差异数量">
          </el-table-column>
          <el-table-column
            prop="statusName"
            label="异常状态">
          </el-table-column>
          <el-table-column label="操作" width="240px">
            <template slot-scope='scope'>
              <el-button type="primary" v-if="scope.row.num>0 && scope.row.status!=2"
                         @click.stop="handleOperateClick(scope.row,'移库')">移库
              </el-button>
              <el-button type="primary" v-if="scope.row.num>0 && scope.row.status!=2"
                         @click.stop="handleOperateClick(scope.row,'归还到原仓库')">归还到原仓库
              </el-button>
              <el-button type="primary" v-if="scope.row.num<0 && scope.row.status!=2"
                         @click.stop="handleOperateClick(scope.row,'报废')">报废
              </el-button>
              <el-button type="primary" v-if="scope.row.num<0 && scope.row.status!=2"
                         @click.stop="handleOperateClick(scope.row,'找回')">找回
              </el-button>
              <el-button type="primary" v-if="scope.row.num<0 && scope.row.status!=2"
                         @click.stop="handleOperateClick(scope.row,'标签替换')">标签替换
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right;margin-top: 20px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 15, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      title="标签替换"
      top="45px"
      append-to-body
      @close="onDialogClose2"
      :visible.sync="replaceDialogVisible"
      width="560px">
      <div>
        <div style="font-weight: 700;font-size: 16px">操作提示</div>
        <div style="line-height: 22px;margin-top: 10px">此操作针对的是器材完好，但是标签损坏的情况；</div>
        <div style="line-height: 22px">需要发行标签并将新标签的ID填入新标签ID输入框，发行标签和输入ID动作不分前后。</div>
        <div v-if="selectDetailData" style="line-height: 22px;margin-top: 6px">器材分类：{{ selectDetailData.parentName }}</div>
        <div v-if="selectDetailData" style="line-height: 22px">器材名称：{{ selectDetailData.equipmentTypeName }}</div>
        <div v-if="selectDetailData" style="line-height: 22px">旧标签ID：{{ selectDetailData.labelId }}</div>
        <div style="line-height: 22px">新标签ID：<span
          style="font-weight: 700;font-size:16px;font-style: italic ">{{ newLabelId }}</span></div>
        <div style="margin-top: 10px">
          <el-button type="primary" @click="createNewLabel">生成标签
          </el-button>
          <el-button type="primary" @click="releaseLabel">发行标签
          </el-button>
          <el-button type="primary" @click="replaceLabel">提交
          </el-button>
          <el-button type="primary" @click="replaceDialogVisible=false">关闭
          </el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :title="selectStock==0?'处理在外数量异常':'处理在库数量异常'"
      top="45px"
      append-to-body
      @close="onDialogClose"
      :visible.sync="dialogVisible2"
      width="560px">
      <div>
        <div v-if="selectDetailData" style="line-height: 22px">器材分类：{{ selectDetailData.parentName }}</div>
        <div v-if="selectDetailData" style="line-height: 22px">器材名称：{{ selectDetailData.equipmentTypeName }}</div>
        <div style="line-height: 22px">差异数量：{{ tableData.length > 0 && tableData[0].num }}</div>
        <div style="line-height: 22px">异常状态：{{ tableData.length > 0 && tableData[0].statusName }}</div>
        <div style="margin-top: 10px">
          <el-button
            type="primary"
            v-if="tableData.length>0 &&tableData[0].num>0 && tableData[0].status!=2"
            @click="handleOperateClick(tableData[0],'移库')">移库
          </el-button>
          <el-button
            type="primary"
            v-if="tableData.length>0 &&tableData[0].num<0 && tableData[0].status!=2"
            @click="handleOperateClick(tableData[0],'报废')">报废
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="标签发行"
      top="25px"
      :visible.sync="issueDialogVisible"
      @close="onIssueDialogClose"
      append-to-body
      width="680px">
      <LabelIssueComponent
        :form="labelForm"
        :message="issueMessage"
        ref="LabelIssueComponent"/>
      <span slot="footer">
        <el-button @click="issueDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="器材轨迹"
      top="45px"
      v-if="mapDialogVisible"
      append-to-body
      :visible.sync="mapDialogVisible">
      <EquipmentTrackComponent
        :id="selectedMapId"/>
    </el-dialog>
  </div>
</template>

<script>
import { getInventoryExceptionList, queryInventoryDetails, handleInventoryException } from '@/api/inventory'
import EquipmentTrackComponent from '../EquipmentTrackComponent'
import LabelIssueComponent from '../LabelIssueComponent'
import { getLabelToIssue, confirmLabelIssue } from '@/api/purchase'

export default {
  name: 'InventoryException',
  components: {
    EquipmentTrackComponent,
    LabelIssueComponent
  },
  props: {
    form: {
      type: Object,
      default: function() {
        return {
          id: '',
          equipmentTypeId: [],
          outNum: 0,
          outStockNum: 0,
          labelWay: '',
          shelfLife: ''
        }
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      replaceDialogVisible: false,
      dialogVisible2: false,
      treeProps: { value: 'id', label: 'name' },
      detailTableData: [],
      currentPage: 1,
      total: 0,
      pageSize: 10,
      currentDetailPage: 1,
      detailTotal: 0,
      detailPageSize: 10,
      tableData: [],
      newLabelId: '',
      hasReleasedNewLabel: false,
      replaceData: {},
      selectDetailData: null,
      selectStock: 0,
      mapDialogVisible: false,
      selectedMapId: '',
      issueDialogVisible: false,
      labelForm: [],
      issueMessage: ''
    }
  },
  mounted() {
    this.getDetailTableData()
  },
  methods: {
    handleSizeChange: function(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTableData()
    },
    handleCurrentChange: function(val) {
      this.currentPage = val
      this.getTableData()
    },
    handleExceptionSizeChange: function(val) {
      this.detailPageSize = val
      this.currentDetailPage = 1
      this.getDetailTableData()
    },
    handleExceptionCurrentChange: function(val) {
      this.currentPage = val
      this.getDetailTableData()
    },
    getDetailTableData() {
      const param = { page: this.currentPage, rows: this.pageSize, busCheckId: this.form.id }
      queryInventoryDetails(param).then(res => {
        this.detailTableData = res.resultData
        this.detailTotal = res.total
      })
    },
    getTableData() {
      const param = { page: this.currentPage, rows: this.pageSize, checkDetailsId: this.selectDetailData.id }
      Object.assign(param, this.selectDetailData)
      param.isStock = this.selectStock
      getInventoryExceptionList(param).then(res => {
        this.tableData = res.resultData
        this.total = res.total
        if (this.tableData.length == 0) {
          this.dialogVisible = false
          this.getDetailTableData()
        }
      })
    },
    handleExceptionOperateClick(row, tag) {
      this.selectDetailData = row
      if (tag == '处理在库数量异常') {
        this.selectStock = 1
        this.onHandleException(1)
      } else if (tag == '处理在外数量异常') {
        this.selectStock = 0
        this.onHandleException(0)
      }
    },
    handleOperateClick(row, tag) {
      this.selectDetailData.labelId = row.labelId
      const h = this.$createElement
      if (tag == '移库') {
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('div', { style: 'text-align: center' }, '系统自动完成移库操作，本物资的所属仓库从原来仓库变更为本仓库；'),
            h('div', { style: 'text-align: center' }, '请及时将此多出物资放回仓库，确保数据准确；'),
            h('div', { style: 'text-align: center' }, '【这个很重要，系统不再做内外的判断，通过管理的方式控制移库一定是在库的移库】'),
            h('div', { style: 'text-align: center' }, '如果对方已经做报废处理，则系统会自动将对方的报废状态设置为无效；'),
            h('div', { style: 'text-align: center' }, '此操作可确保总体物资数量一致')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定移库',
          cancelButtonText: '取消'
        }).then(action => {
          this.handleException(row, 1)
        })
      } else if (tag == '归还到原仓库') {
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('div', { style: 'text-align: center' }, '请将此物资移出仓库，避免再次扫描到；'),
            h('div', { style: 'text-align: center' }, '并及时归还给原归属仓库；')
          ]),
          showCancelButton: false,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          this.handleException(row, 2)
        })
      } else if (tag == '找回') {
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('div', { style: 'text-align: center' }, '请及时依据物资跟踪信息找回物资，'),
            h('div', { style: 'text-align: center' }, '并放入仓库后针对此物资重新盘点；')
          ]),
          showCancelButton: false,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          this.handleException(row, 4)
        })
      } else if (tag == '标签替换') {
        this.newLabelId = ''
        this.hasReleasedNewLabel = false
        this.replaceData = row
        this.replaceDialogVisible = true
      } else if (tag == '报废') {
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('div', { style: 'text-align: center' }, '报废处理后仓库物资数量将减少；'),
            h('div', { style: 'text-align: center' }, '如果其他仓库在此之后进行了移库操作；'),
            h('div', { style: 'text-align: center' }, '则系统自动设置此报废无效；')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定报废',
          cancelButtonText: '取消'
        }).then(action => {
          this.handleException(row, 3)
        })
      }
    },
    handleException(row, operType) {
      // 如果是一堆
      const param = {}
      Object.assign(param, row)
      param.operType = operType
      param.isStock = this.selectStock
      if (operType == 5) {
        param.newLabelId = this.newLabelId
      }
      handleInventoryException(param).then(res => {
        // 如果是一对一，则刷新列表，如果是一对多，则退出对话框
        if (this.selectDetailData.labelWay == '1') {
          this.getTableData()
        } else {
          this.dialogVisible2 = false
          this.getDetailTableData()
        }
      })
    },
    onHandleException() {
      this.currentPage = 0
      this.total = 0
      this.pageSize = 10
      this.getTableData()
      if (this.selectDetailData.labelWay == '1') {
        this.dialogVisible = true
      } else if (this.selectDetailData.labelWay == '2') {
        this.dialogVisible2 = true
      }
    },
    releaseLabel() {
      // todo 调用本地发卡器生成物理标签
      confirmLabelIssue({ tagId: this.newLabelId }).then(res => {
        this.hasReleasedNewLabel = true
        this.$message({type:'success',message:'发行成功!'})
      })
    },
    createNewLabel() {
      const param = {
        batchNo: this.replaceData.batchNo,
        equipmentTypeId: this.replaceData.equipmentTypeId,
        equipmentTypeCode: this.replaceData.equipmentTypeCode,
        releaseNum: 1
      }
      getLabelToIssue(param).then(res => {
        if (res.resultData.length > 0) {
          res.resultData.forEach(item => {
            item.status = -1
          })
          this.newLabelId = res.resultData[0].tagId
        } else {
          this.$message({
            type: 'error',
            message: '生成标签失败'
          })
        }
      })
    },
    replaceLabel() {
      if(!this.newLabelId||this.newLabelId==''||this.hasReleasedNewLabel==false){
        this.$message({type:'error',message:'请发布新的标签！'})
        return
      }
      this.handleException(this.replaceData, 5)
      this.replaceDialogVisible = false
    },
    onDialogClose() {
      this.getDetailTableData()
    },
    onDialogClose2() {
      this.getTableData()
    },
    onIssueDialogClose() {
      // this.getDetailTableData()
    },
    goMap(row, column, event) {
      this.selectedMapId = row.equipmentId + ''
      this.mapDialogVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dd {
  text-align: center;
}
</style>
